package com.fs.controller.v1;

import com.fs.controller.PicFitUtil;
import com.fs.controller.vo.cleaner.ReqAddCleanerByRoom;
import com.fs.controller.vo.shop.RespGetPics;
import com.fs.global.config.CustomConfig;
import com.fs.global.init.RoleName;
import com.fs.service.RoomService;
import com.fs.service.bo.room.BoCleanerCreateParam;
import com.fs.service.bo.room.BoRoom;
import com.fs.service.bo.shop.BoShop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Api(tags = "房间API", description = "管理员账户使用")
@RestController
@RequestMapping("/v1/room")
@RequiresRoles(RoleName.ADMIN)
@Validated
public class RoomController {

    private final RoomService roomService;
    private final PicFitUtil picFitUtil;
    private final CustomConfig config;

    public RoomController(RoomService roomService, PicFitUtil picFitUtil, CustomConfig config) {
        this.roomService = roomService;
        this.picFitUtil = picFitUtil;
        this.config = config;
    }

    @ApiOperation("上传房间图片")
    @PostMapping("/upload")
    public String uploadPic(@RequestParam(value = "file") MultipartFile[] files, Integer roomId)
            throws IOException {

        roomService.getByID(roomId);
        String fileSaveDir = picFitUtil.getAbsImageDirOfRoom(roomId);

        for (MultipartFile file : files) {
            InputStream inputStream = file.getInputStream();
            OutputStream outputStream = new FileOutputStream(fileSaveDir + File.separator + file.getOriginalFilename());
            byte[] bytes = new byte[1024];
            while (inputStream.read(bytes) != -1) {
                outputStream.write(bytes);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        }
        return "上传成功";
    }

    @ApiOperation("删除房间照片")
    @DeleteMapping("/pics")
    public void deleteRoomPic(@RequestBody List<String> paths) {
        for (String path : paths) {
            String absPicPath = String.join(File.separator, config.getPicfitDir(), path);
            File file = new File(absPicPath);
            if(file.exists()){
                file.delete();
            }
        }
    }

}
